package com.linxin.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linxin.reggie.common.Result;
import com.linxin.reggie.dto.DishDto;
import com.linxin.reggie.entity.Category;
import com.linxin.reggie.entity.Dish;
import com.linxin.reggie.entity.DishFlavor;
import com.linxin.reggie.entity.SetmealDish;
import com.linxin.reggie.service.CategoryService;
import com.linxin.reggie.service.DishFlavorService;
import com.linxin.reggie.service.DishService;
import com.linxin.reggie.service.SetmealDishService;
import com.sun.org.glassfish.external.probe.provider.annotations.ProbeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 根据传入的json保存菜品
     *
     * @param dishDto 包括dish和dishFlavor(数据传输对象)
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto) {
        log.info("dishDto接收的数据为: {}", dishDto);

        // dishService扩展方法
        dishService.saveDishWithFlavor(dishDto);

        // 添加后,清除对应分类的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return Result.success("新增菜品成功!!!");

    }

    /**
     * 分页展示菜品信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name) {
        log.info("菜品分页 page: {}, pageSize: {}, name: {}", page, pageSize, name);

        // 分页构造器对象
        // 用于给dishDtoPageInfo赋值
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        // 需要返回dishDto这种泛型, 才能展示产品的分类信息
        Page<DishDto> dishDtoPageInfo = new Page<>(page, pageSize);

        // 条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件
        queryWrapper.like(name != null, Dish::getName, name);
        // 添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        // 执行分页查询
        dishService.page(pageInfo, queryWrapper);

        // 将查询的pageInfo复制给dishDtoPageInfo, records不用复制
        // pageInfo的records的保存的查询数据, 但是泛型是dish, 前端需要的泛型为dishDto
        // BeanUtils.copyProperties(数据, 需要复制的, "忽略的东西");
        BeanUtils.copyProperties(pageInfo, dishDtoPageInfo, "records");

        // records单独处理
        // 获取pageInfo的records
        List<Dish> records = pageInfo.getRecords();

        // 根据pageInfo的records, 完善dishDtoPageInfo的records
        List<DishDto> dishDtoList = records.stream().map((item) -> {
            // 赋值给这个对象
            DishDto dishDto = new DishDto();

            // 将item的全部数据赋值给dishDto, 里面没有categoryName
            BeanUtils.copyProperties(item, dishDto);

            // 获取dish的分类id
            Long categoryId = item.getCategoryId();

            // 根据分类id到分类表中查询分类名
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();

            // 将categoryName赋值给dishDto的categoryName
            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPageInfo.setRecords(dishDtoList);

        // 响应前端
        return Result.success(dishDtoPageInfo);
    }

    /**
     * 根据菜品id查询对应的dishDto数据, 用于回写修改菜品
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id) {
        log.info("需要查询的id为: {}", id);

        // 调用dishService的查询方法, 需要在dishService增加对应的方法
        DishDto dishDto = dishService.getDishWithFlavor(id);

        return Result.success(dishDto);
    }

    /**
     * 更新菜信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto) {
        log.info("更新菜品信息, dishDto接收的数据为: {}", dishDto);

        // dishService扩展方法
        dishService.updateDishWithFlavor(dishDto);

        // 更新后,清除对应分类的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return Result.success("菜品数据更新成功!!!");
    }

    /**
     * 根据传入的id, 删除菜品信息(包括口味)(菜品停售才能删除)
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> delete(Long[] ids) {
        log.info("需要删除的菜品id为: {}", ids);

        // 调用dishService的删除方法删除, 包括对应的口味
        dishService.deleteDishWithFlavor(ids);

        return Result.success("菜品删除成功");
    }


    /**
     * 根据请求的数据, 设置启售或者停售
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> setStatus(@PathVariable int status, Long[] ids) {
        log.info("菜品状态为: {}, 需要设置的id为: {}", status, Arrays.toString(ids));

        // 根据状态判断 启售1 或者 停售0
        for (int i = 0; i < ids.length; i++) {
            // 根据id获取dish表的信息
            LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            // 等值查询
            dishLambdaQueryWrapper.eq(Dish::getId, ids[i]);
            // 获取数据
            Dish dish = dishService.getOne(dishLambdaQueryWrapper);
            // 设置状态
            dish.setStatus(status);
            // 更新
            dishService.updateById(dish);
        }

        // 返回信息
        if (status == 1) {
            return Result.success("启售成功!!!");
        } else {
            return Result.success("停售成功!!!");
        }
    }

    /**
     * 根据分类id查询菜品(前端传入的是Long categoryId, 可以使用dish接收)
     * 需要修改这个方法, 返回值改为dishDto的集合, 方便前端展示
     *
     * @param dish
     * @return
     */
    /*@GetMapping("/list")
    public Result<List<Dish>> list(Dish dish) {
        // 构造条件查询
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据Long categoryId等值查询
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 状态为启售1等值查询
        dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
        // 添加排序条件
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        // 返回list
        return Result.success(list);
    }*/

    /**
     * 查询菜品分类
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;

        // 先从redis查询缓存数据
        // 构建key
        String dishKey = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        // 从redis获取数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(dishKey);
        if (dishDtoList != null) {
            return Result.success(dishDtoList);
        }

        // 缓存没有则查询数据库

        // 构造条件查询
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据Long categoryId等值查询
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 状态为启售1等值查询
        dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
        // 添加排序条件
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        // 获取dish的集合
        List<Dish> dishList = dishService.list(dishLambdaQueryWrapper);

        // 流处理dishList集合, 转化为dishDto
        dishDtoList = dishList.stream().map((item) -> {
            // 创建返回对象
            DishDto dishDto = new DishDto();
            // 将dish的数据复制到dishDto
            BeanUtils.copyProperties(item, dishDto);

            // 查询分类id
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            // 不为空则添加到dishDto
            if (category != null) {
                String name = category.getName();
                dishDto.setCategoryName(name);
            }

            // 获取菜品id
            Long dishId = item.getId();
            // 在口味表中查询对应的口味
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            // 等值查询
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            // 获取集合
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);

            // 将dishFlavors赋值给dishDto
            dishDto.setFlavors(dishFlavors);

            return dishDto;
        }).collect(Collectors.toList());

        // 将查询的数据存储到redis缓存
        redisTemplate.opsForValue().set(dishKey, dishDtoList, 60, TimeUnit.MINUTES);

        // 返回list
        return Result.success(dishDtoList);
    }

    /**
     * 点击查看套餐中的菜品
     */
    @GetMapping("/dish/{id}")
    public Result<List<DishDto>> dish(@PathVariable("id") Long SetmealId) {
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, SetmealId);
        //获取套餐里面的所有菜品  这个就是SetmealDish表里面的数据
        List<SetmealDish> list = setmealDishService.list(queryWrapper);

        List<DishDto> dishDtos = list.stream().map((setmealDish) -> {
            DishDto dishDto = new DishDto();
            //将套餐菜品关系表中的数据拷贝到dishDto中
            BeanUtils.copyProperties(setmealDish, dishDto);
            //这里是为了把套餐中的菜品的基本信息填充到dto中，比如菜品描述，菜品图片等菜品的基本信息
            Long dishId = setmealDish.getDishId();
            Dish dish = dishService.getById(dishId);
            //将菜品信息拷贝到dishDto中
            BeanUtils.copyProperties(dish, dishDto);

            return dishDto;
        }).collect(Collectors.toList());

        return Result.success(dishDtos);
    }
}
